package project.crawler.parser;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

class ParserUtils {

	static Element getElement(Element body, String attrName, String attrValue,
			String tagName) {
		Elements elems = body.getElementsByAttributeValue(attrName, attrValue);
		return assertOneElement(elems, tagName);
	}

	static String getCanonURL(Element head) {
		Element elem = ParserUtils.getElement(head, "rel", "canonical", "link");
		return elem.attr("href");
	}

	static long parseDate(String date) {
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return f.parse(date).getTime();
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}

	static Element assertOneElement(Elements elems, String expectedType) {
		if (elems.size() != 1 || !elems.first().tagName().equals(expectedType)) {
			throw new RuntimeException(elems.toString());
		}
		return elems.first();
	}

	static long getLongFromPattern(Pattern patt, String str) {
		Matcher m = patt.matcher(str);
		if (!m.matches()) {
			throw new RuntimeException(str);
		}
		return Long.parseLong(m.group(1));
	}

}
